"""
物流管理API
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity

from app.models.logistics import Logistics, LogisticsProvider, LogisticsStatus, TrackingNode
from app.models.order import Order
from app.models.user import User
from app.schemas.logistics import LogisticsSchema, LogisticsProviderSchema, TrackingNodeSchema
from app.extensions import db, socketio
from app.utils.auth import admin_required

logistics_bp = Blueprint('logistics', __name__)

@logistics_bp.route('/providers', methods=['GET'])
@jwt_required()
def get_logistics_providers():
    """获取所有物流服务商"""
    providers = LogisticsProvider.query.all()
    return jsonify(LogisticsProviderSchema(many=True).dump(providers)), 200

@logistics_bp.route('/providers/<int:provider_id>', methods=['GET'])
@jwt_required()
def get_logistics_provider(provider_id):
    """获取特定物流服务商"""
    provider = LogisticsProvider.query.get(provider_id)
    
    if not provider:
        return jsonify({"msg": "物流服务商不存在"}), 404
    
    return jsonify(LogisticsProviderSchema().dump(provider)), 200

@logistics_bp.route('/providers', methods=['POST'])
@jwt_required()
@admin_required
def create_logistics_provider():
    """创建物流服务商"""
    data = request.get_json()
    
    if not data.get('name'):
        return jsonify({"msg": "请提供物流服务商名称"}), 400
    
    try:
        provider = LogisticsProvider(
            name=data.get('name'),
            description=data.get('description'),
            website=data.get('website'),
            contact=data.get('contact'),
            api_key=data.get('api_key'),
            api_url=data.get('api_url')
        )
        
        db.session.add(provider)
        db.session.commit()
        
        return jsonify({
            "msg": "物流服务商创建成功",
            "provider": LogisticsProviderSchema().dump(provider)
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"创建物流服务商失败: {str(e)}"}), 500

@logistics_bp.route('/providers/<int:provider_id>', methods=['PUT'])
@jwt_required()
@admin_required
def update_logistics_provider(provider_id):
    """更新物流服务商信息"""
    provider = LogisticsProvider.query.get(provider_id)
    
    if not provider:
        return jsonify({"msg": "物流服务商不存在"}), 404
    
    data = request.get_json()
    
    try:
        if 'name' in data:
            provider.name = data.get('name')
        if 'description' in data:
            provider.description = data.get('description')
        if 'website' in data:
            provider.website = data.get('website')
        if 'contact' in data:
            provider.contact = data.get('contact')
        if 'api_key' in data:
            provider.api_key = data.get('api_key')
        if 'api_url' in data:
            provider.api_url = data.get('api_url')
        
        db.session.commit()
        
        return jsonify({
            "msg": "物流服务商更新成功",
            "provider": LogisticsProviderSchema().dump(provider)
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"更新物流服务商失败: {str(e)}"}), 500

@logistics_bp.route('/providers/<int:provider_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_logistics_provider(provider_id):
    """删除物流服务商"""
    provider = LogisticsProvider.query.get(provider_id)
    
    if not provider:
        return jsonify({"msg": "物流服务商不存在"}), 404
    
    # 检查是否有关联的物流单
    if Logistics.query.filter_by(provider_id=provider_id).first():
        return jsonify({"msg": "该物流服务商有关联的物流单，无法删除"}), 400
    
    try:
        db.session.delete(provider)
        db.session.commit()
        
        return jsonify({"msg": "物流服务商删除成功"}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"删除物流服务商失败: {str(e)}"}), 500

@logistics_bp.route('/', methods=['GET'])
@jwt_required()
def get_logistics():
    """获取所有物流信息"""
    # 这里需要实现物流查询逻辑
    return jsonify({"message": "物流API - 获取所有物流信息"}), 200

@logistics_bp.route('/<int:logistics_id>', methods=['GET'])
@jwt_required()
def get_logistics_detail(logistics_id):
    """获取物流单详情"""
    current_user_id = get_jwt_identity()
    current_user = User.query.get(current_user_id)
    
    logistics = Logistics.query.get(logistics_id)
    
    if not logistics:
        return jsonify({"msg": "物流单不存在"}), 404
    
    # 非管理员只能查看关联自己订单的物流单
    if not current_user.is_admin:
        order = Order.query.get(logistics.order_id)
        if not order or order.user_id != current_user_id:
            return jsonify({"msg": "无权限查看此物流单"}), 403
    
    return jsonify(LogisticsSchema().dump(logistics)), 200

@logistics_bp.route('', methods=['POST'])
@jwt_required()
@admin_required
def create_logistics():
    """创建物流单"""
    data = request.get_json()
    
    if not data.get('order_id') or not data.get('provider_id'):
        return jsonify({"msg": "请提供订单ID和物流服务商ID"}), 400
    
    # 验证订单存在
    order = Order.query.get(data.get('order_id'))
    if not order:
        return jsonify({"msg": "订单不存在"}), 404
    
    # 验证物流服务商存在
    provider = LogisticsProvider.query.get(data.get('provider_id'))
    if not provider:
        return jsonify({"msg": "物流服务商不存在"}), 404
    
    # 检查是否已有关联物流单
    if Logistics.query.filter_by(order_id=data.get('order_id')).first():
        return jsonify({"msg": "该订单已有关联的物流单"}), 400
    
    try:
        logistics = Logistics(
            order_id=data.get('order_id'),
            provider_id=data.get('provider_id'),
            tracking_number=data.get('tracking_number'),
            status=LogisticsStatus.PROCESSING.value,
            shipping_address=data.get('shipping_address') or order.shipping_address,
            estimated_delivery=data.get('estimated_delivery')
        )
        
        db.session.add(logistics)
        db.session.flush()  # 获取物流单ID
        
        # 创建初始跟踪节点
        tracking_node = TrackingNode(
            logistics_id=logistics.id,
            status=LogisticsStatus.PROCESSING.value,
            location=data.get('location', '物流中心'),
            description="物流单已创建"
        )
        
        db.session.add(tracking_node)
        db.session.commit()
        
        # 通过WebSocket发送物流状态更新通知
        socketio.emit('logistics_update', {
            'logistics_id': logistics.id,
            'order_id': logistics.order_id,
            'status': logistics.status,
            'tracking_number': logistics.tracking_number
        })
        
        return jsonify({
            "msg": "物流单创建成功",
            "logistics": LogisticsSchema().dump(logistics)
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"创建物流单失败: {str(e)}"}), 500

@logistics_bp.route('/<int:logistics_id>/status', methods=['PUT'])
@jwt_required()
@admin_required
def update_logistics_status(logistics_id):
    """更新物流状态"""
    logistics = Logistics.query.get(logistics_id)
    
    if not logistics:
        return jsonify({"msg": "物流单不存在"}), 404
    
    data = request.get_json()
    new_status = data.get('status')
    
    if not new_status:
        return jsonify({"msg": "请提供新的物流状态"}), 400
    
    try:
        # 验证状态值是否有效
        if new_status not in [status.value for status in LogisticsStatus]:
            return jsonify({"msg": "无效的物流状态"}), 400
        
        # 更新物流状态
        logistics.status = new_status
        
        # 创建新的跟踪节点
        tracking_node = TrackingNode(
            logistics_id=logistics.id,
            status=new_status,
            location=data.get('location', ''),
            description=data.get('description', '')
        )
        
        db.session.add(tracking_node)
        db.session.commit()
        
        # 通过WebSocket发送物流状态更新通知
        socketio.emit('logistics_update', {
            'logistics_id': logistics.id,
            'order_id': logistics.order_id,
            'status': logistics.status,
            'tracking_number': logistics.tracking_number,
            'tracking_node': TrackingNodeSchema().dump(tracking_node)
        })
        
        return jsonify({
            "msg": "物流状态更新成功",
            "logistics": LogisticsSchema().dump(logistics)
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"更新物流状态失败: {str(e)}"}), 500

@logistics_bp.route('/<int:logistics_id>/tracking', methods=['GET'])
@jwt_required()
def get_tracking_history(logistics_id):
    """获取物流跟踪历史"""
    current_user_id = get_jwt_identity()
    current_user = User.query.get(current_user_id)
    
    logistics = Logistics.query.get(logistics_id)
    
    if not logistics:
        return jsonify({"msg": "物流单不存在"}), 404
    
    # 非管理员只能查看关联自己订单的物流单
    if not current_user.is_admin:
        order = Order.query.get(logistics.order_id)
        if not order or order.user_id != current_user_id:
            return jsonify({"msg": "无权限查看此物流单"}), 403
    
    # 获取跟踪节点并按时间降序排序
    tracking_nodes = TrackingNode.query.filter_by(logistics_id=logistics_id).order_by(TrackingNode.created_at.desc()).all()
    
    return jsonify(TrackingNodeSchema(many=True).dump(tracking_nodes)), 200 